<template>
  <div id="myCode">
    <Header :showheaderLeft="false" :showBack="true" :isTitle="true" :showTitle="true"></Header>
    <div class="rootMain">
      <div class="content">
        <div class="top">
          <p>
            <b>{{$t('m.currency')}}：</b>
            ETH
          </p>
          <p>
            <b>{{$t('m.chainType')}}：</b>ERC20
          </p>
        </div>
        <div class="qrcode">
          <div class="codeImg">
            <img :src="qrcode" alt id="saveCode" />
            <p>{{$t('m.saveCode')}}</p>
          </div>
          <p class="warning">{{$t('m.saveTips')}}</p>
          <p :class="language == 'en_US'?'en_p':''">
            <a
              v-if="!Html5Plus"
              href="javascript:;"
              @click="downloadIamge(qrcode)"
            >{{$t('m.saveCode1')}}</a>
            <small v-else id="downloadSaveCode">{{$t('m.saveCode1')}}</small>
          </p>
        </div>
        <div class="address">
          <p>
            <b>{{$t('m.currencyAddress')}}：</b>
            <span>{{userObj.walletAddress}}</span>
          </p>
          <p :class="language == 'en_US'?'en_p':''">
            <a href="javascript:;" @click="copyShaneUrl()">{{$t('m.copyAddress')}}</a>
          </p>
          <input type="text" :value="userObj.walletAddress" id="copyUrl" v-show="false" />
        </div>
        <!-- <div class="text">
          <h4>{{$t('m.retips')}}：</h4>
          <p>{{$t('m.retips1')}}</p>
          <p>{{$t('m.retips2')}}</p>
          <p>{{$t('m.retips3')}}</p>
          <p>{{$t('m.retips4')}}</p>
        </div>
        <div class="tips">{{$t('m.retips5')}}</div>-->
        <!-- <div class="tips2">{{$t('m.retips6')}}</div> -->
      </div>
    </div>
  </div>
</template>
<script>
import Services from "@/service/index.js";
import { mapMutations, mapState } from "vuex";
import Header from "@/components/header";
import { Dialog, Toast } from "vant";
import QRCode from "qrcode";
export default {
  data() {
    return {
      loginToken: "",
      userObj: {},
      url: "",
      qrcode: "",
      type: 1,
      Html5Plus: false,
      language: "",
      time: ""
    };
  },
  created() {
    this.changeTitle(this.$t("m.recharge"));
    this.loginToken = localStorage.getItem("token")
      ? localStorage.getItem("token")
      : "";
    this.userObj = localStorage.getItem("userObj")
      ? JSON.parse(localStorage.getItem("userObj"))
      : "";
    this.language = localStorage.getItem("language");
    this.url = this.userObj.walletAddress;
    if (navigator.userAgent.indexOf("Html5Plus") > -1) {
      this.Html5Plus = true;
    } else {
      this.Html5Plus = false;
    }
    if (this.$route.query.type == 1) {
      this.type = 1;
    } else {
      this.type = 2;
    }
    // Services.transfer({
    //   token: this.loginToken,
    //   amount: 10,
    //   fromType: 5
    // }).then(res=>{
    //   console.log(res);
    // });
  },
  components: { Header, QRCode },
  computed: {},
  mounted() {
    // alert(navigator.)
    //生成二维码
    QRCode.toDataURL(this.url, {
      version: 7, //这个是版本号，
      errorCorrectionLevel: "Q", //这个是容错率,(建议选较低)更高的级别可以识别
      width: 280,
      height: 280, //设置二维码图片大小
      margin: 0
    })
      .then(url => {
        //这个url是二维码生成地址，也就是相当于图片地址
        //        console.log(url);
        this.qrcode = url; //这个是vue实例全局的变量，赋值给他。后面会用在img的src属性上
      })
      .catch(err => {
        console.error(err); //这里看不懂的话去看一下Promise（then, catch）
      });
    //_________________________________
    // Android下载二维码
    if (this.Html5Plus) {
      this.mui.init({
        gestureConfig: {
          longtap: true
        }
      });
      var that = this;
      this.mui.plusReady(function() {
        document
          .getElementById("downloadSaveCode")
          .addEventListener("tap", function(event) {
            var name = event.target.tagName;
            that.getNowTime();
            if (name.toLowerCase() == "small") {
              var baseImgFile = (function(uid, base64, quality) {
                quality = quality || 10;
                // callback = callback || $.noop;
                var bitmap = new plus.nativeObj.Bitmap();
                // 从本地加载Bitmap图片
                bitmap.loadBase64Data(
                  base64,
                  function() {
                    bitmap.save(
                      "_doc/" + uid + "_" + that.time + ".jpg",
                      {
                        overwrite: true,
                        quality: quality
                      },
                      function(i) {
                        plus.gallery.save(
                          "_doc/" + uid + "_" + that.time + ".jpg",
                          function() {
                            Toast(that.$t("m.saveCode4"));
                          }
                        );
                      },
                      function(e) {
                        Toast(that.$t("m.saveCode5"));
                      }
                    );
                  },
                  function(e) {
                    Toast(that.$t("m.saveCode5"));
                  }
                );
              })("qrcode", that.qrcode, 100);
            }
          });
        // 长按保存二维码
        document
          .getElementById("saveCode")
          .addEventListener("longtap", function(event) {
            var name = event.target.tagName;
            that.getNowTime();
            if (name.toLowerCase() === "img") {
              // var imgUrl = event.target.src;
              var baseImgFile = (function(uid, base64, quality) {
                quality = quality || 10;
                // callback = callback || $.noop;
                var bitmap = new plus.nativeObj.Bitmap();
                // 从本地加载Bitmap图片
                bitmap.loadBase64Data(
                  base64,
                  function() {
                    bitmap.save(
                      "_doc/" + uid + "_" + that.time + ".jpg",
                      {
                        overwrite: true,
                        quality: quality
                      },
                      function(i) {
                        plus.gallery.save(
                          "_doc/" + uid + "_" + that.time + ".jpg",
                          function() {
                            Toast(that.$t("m.saveCode4"));
                          }
                        );
                      },
                      function(e) {
                        Toast(that.$t("m.saveCode5"));
                      }
                    );
                  },
                  function(e) {
                    Toast(that.$t("m.saveCode5"));
                  }
                );
              })("qrcode", that.qrcode, 100);
            }
          });
      });
    }
    // end
  },
  methods: {
    ...mapMutations(["changeTitle", "changetabbarIndex"]),
    getNowTime() {
      this.time = new Date().getTime();
    },
    copyShaneUrl() {
      this.copy("copyUrl", "value");
    },
    copy(id, attr) {
      let target = null;
      if (attr) {
        target = document.createElement("div");
        target.id = "tempTarget";
        target.style.opacity = "0";
        if (id) {
          let curNode = document.querySelector("#" + id);
          target.innerText = curNode[attr];
        } else {
          target.innerText = attr;
        }
        document.body.appendChild(target);
      } else {
        target = document.querySelector("#" + id);
      }

      try {
        let range = document.createRange();
        range.selectNode(target);
        window.getSelection().removeAllRanges();
        window.getSelection().addRange(range);
        document.execCommand("copy");
        window.getSelection().removeAllRanges();
        Toast(this.$t("m.successfulCopy"));
      } catch (e) {
        Toast(this.$t("m.replicationFailed"));
      }

      if (attr) {
        // remove temp target
        target.parentElement.removeChild(target);
      }
    },
    //下载base64图片
    base64ToBlob(code) {
      let parts = code.split(";base64,");
      let contentType = parts[0].split(":")[1];
      let raw = window.atob(parts[1]);
      let rawLength = raw.length;
      let uInt8Array = new Uint8Array(rawLength);
      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
      }
      return new Blob([uInt8Array], {
        type: contentType
      });
    },
    // alert(imgsrc);
    downloadFile(content, fileName) {
      let aLink = document.createElement("a");
      let blob = this.base64ToBlob(content); //new Blob([content]);
      let evt = document.createEvent("HTMLEvents");
      evt.initEvent("click", true, true); //initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
      aLink.download = fileName;
      aLink.href = URL.createObjectURL(blob);
      aLink.click();
    },
    downloadIamge(imgsrc) {
      if (!!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
        Toast(this.$t("m.saveCode2"));
        return;
      }
      this.downloadFile(imgsrc, "测试");
      // // 下载图片地址和图片名
      // var image = new Image();
      // // 解决跨域 Canvas 污染问题
      // image.setAttribute("crossOrigin", "anonymous");
      // image.onload = function() {
      //   var canvas = document.createElement("canvas");
      //   canvas.width = image.width;
      //   canvas.height = image.height;
      //   var context = canvas.getContext("2d");
      //   context.drawImage(image, 0, 0, image.width, image.height);
      //   var url = canvas.toDataURL("image/png"); //得到图片的base64编码数据

      //   var a = document.createElement("a"); // 生成一个a元素
      //   var event = new MouseEvent("click"); // 创建一个单击事件
      //   a.download = "qrcode.png"; // 设置图片名称
      //   a.href = url; // 将生成的URL设置为a.href属性
      //   a.dispatchEvent(event); // 触发a的单击事件
      // };
      // image.src = imgsrc;
    }
  },
  destroyed() {
    this.time = "";
  }
};
</script>
<style lang="scss" scoped type="text/scss">
#myCode {
  .rootMain {
    height: calc(100% - 0.88rem);
    top: 0.88rem;
    overflow-y: auto;
    .content {
      padding: 0.3rem 0.5rem;
      border-radius: 0.2rem 0.2rem 0 0;
    }
    .top {
      margin-bottom: 0.2rem;
      p {
        text-align: center;
        font-weight: 600;
        margin: 0.1rem 0;
      }
    }

    .qrcode,
    .address {
      text-align: center;
      .codeImg {
        margin: 0 auto;
        margin-bottom: 0.2rem;
        width: 3.71rem;
        height: 3.96rem;
        padding: 0.22rem 0.22rem 0.1rem;
        overflow: hidden;
        background: #fff;
        img {
          width: 3.29rem;
          height: 3.29rem;
        }
        border: 1px solid #ddd;
        p {
          color: #ababab;
        }
      }
      .warning {
        color: #f10;
        font-size: 0.22rem;
        margin-bottom: 0.8rem;
      }
      p {
        a,
        small {
          margin: 0 auto;
          width: 4rem;
          height: 0.85rem;
          display: inline-block;
          line-height: 0.85rem;
          font-size: 0.28rem;
          letter-spacing: 0.05rem;
          text-align: center;
          border-radius: 0.1rem;
          color: #fff;
          background: linear-gradient(to right, #43434e, #727181);
        }
        &.en_p {
          a {
            letter-spacing: 0;
            font-size: 0.24rem;
          }
        }
      }
    }
    .address {
      p:first-child {
        padding: 0.6rem 0 0.4rem;
        text-align: left;
        display: flex;
        font-weight: 600;
        span {
          width: calc(100% - 1.6rem);
          word-wrap: break-word;
        }
      }
    }
    .text {
      // margin-top: 0.4rem;
      padding-top: 0.2rem;
      // border-top: 1px solid #2e303c;
      h4 {
        font-size: 0.28rem;
        font-weight: 600;
        color: #40404c;
        margin-bottom: 0.3rem;
      }
      p {
        padding-top: 0.1rem;
        text-indent: 0.2rem;
        color: #888;
      }
    }
    .tips {
      margin-top: 1.5rem;
      font-size: 0.24rem;
      color: #fd6262;
      text-align: center;
    }
    .tips2 {
      margin: 1rem 0;
      font-weight: bold;
      color: #fd6262;
      font-size: 0.3rem;
      text-align: center;
    }
  }
}
</style>